from django.shortcuts import render,HttpResponse,get_object_or_404,redirect
from django.utils.safestring import mark_safe
from django import forms

from ..models import  Device


import base64
import openpyxl
from openpyxl import load_workbook
#导入插件
from ..utlis import fenyezujian
import csv
from datetime import datetime

def netdev(request):
    # 删除设备,根据网页上传递的nid，去数据库中筛选出来进行删除
    nid = request.GET.get('nid')

    #通过nid在数据库中查找出来并删除
    Device.objects.filter(id=nid).delete()

    if request.method == 'GET':

        ## 定义一个空字典
        data_dict={}

        ## 从前端获取数据；前端定义name属性
        search_data1 = request.GET.get("q1","")
        search_data2 = request.GET.get("q2", "")
        search_data3 = request.GET.get("q3", "")

        ## 判断是否有数据,如果有数据则加入到字典中
        if search_data1:
            data_dict["ip__contains"] = search_data1

        ## 判断是否有数据,如果有数据则加入到字典中
        if search_data2:
            data_dict["diqu__contains"] = search_data2

        ## 判断是否有数据,如果有数据则加入到字典中
        if search_data3:
            data_dict["vendor__contains"]= search_data3

        # 地区和设备厂商可以同时搜索
        if search_data2 and search_data3:
            data_dict = {
                "diqu": search_data2,
                "vendor": search_data3,
            }

        ## 定义当前页
        page = int(request.GET.get('page',1))

        ## 定义显示页码数据
        page_size = 10

        ## 定义每页开始位置
        start = (page - 1) * page_size

        ## 定义每页结束位置
        end = page * page_size

        device = Device.objects.filter(**data_dict)[start:end]

        ## 定义总数据
        total_count = Device.objects.filter(**data_dict).count()

        ## 计算出总页面
        total_page_count, div = divmod(total_count,page_size)
        if div:
             total_page_count += 1

        ## 计算出显示当前页的乾5页和后5页
        plus = 5

        if total_page_count <= 2 * plus + 1:
            # 当数据库中数据量少时，小于11页
            start_page = 1  # 开始页=1
            end_page = total_page_count  # 结束也=当前总页码
        else:
            # 当前页码<5时
            if page <= plus:
                start_page = 1
                end_page = 2 * plus + 1
            else:
                # 当前页码 + 要显示的页码 > 总页码时
                if (page + plus) > total_page_count:
                    start_page = total_page_count - 2 * plus
                    end_page = total_page_count
                else:
                    start_page = page - plus
                    end_page = page + plus

        # 页码
        # 定义一个列表
        page_str_list = []

        # 首页
        page_str_list.append('<li><a href="?page={}">首页</a></li>'.format(1))

        # 上一页
        if page > 1:
            prev = '<li><a href="?page={}">上一页</a></li>'.format(
            page - 1)
        else:
            prev = '<li><a href="?page={}">上一页</a></li>'.format(1)
            page_str_list.append(prev)

        # for循环，生成开始页和结束页
        for i in range(start_page, end_page + 1):
            # 如果i=当前页，在前端加个样式，如果不等于当前页则不添加
            if i == page:
                ele = '<li class="active"><a href="?page={}">{}</a></li>'.format(i, i)
            else:
                ele = '<li><a href="?page={}">{}</a></li>'.format(i, i)
                # 将生成出来的页码写入到列表中
            page_str_list.append(ele)

        # 下一页
        if page < total_page_count:
            prev = '<li><a href="?page={}">下一页</a></li>'.format(page + 1)
        else:
            prev = '<li><a href="?page={}">下一页</a></li>'.format(total_page_count)
        page_str_list.append(prev)

        # 尾页
        page_str_list.append('<li><a href="?page={}">尾页</a></li>'.format(total_page_count))

        page_string = mark_safe("".join(page_str_list))

        return render(request, "netdev.html", {"devices": device, "page_string": page_string,"search_data1":search_data1,"search_data2":search_data2,"search_data3":search_data3})





""" 添加设备 """
class DevModeForms(forms.ModelForm):

    class Meta:
        model = Device
        fields = ["ip","dev_name","vendor","xinghao","sn","diqu","weizhi","jigui","username","password","enter","snmp"]

        #定义插件，针对password选项框加密
        widgets = {"password": forms.PasswordInput(render_value=True),"snmp": forms.PasswordInput(render_value=True)}


    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            field.widget.attrs = {"class": "form-control"}


def dev_add(request):
    if request.method == "GET":
        form = DevModeForms()
        return render(request,"devadd.html",{"form":form})

    form = DevModeForms(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/app02/devices/')

    return render(request,"devadd.html",{"form":form})




"""  设备编辑 """
class DevEditModeForms(forms.ModelForm):
    # 定义插件，针对ip_address框禁止编辑的功能;ip 是models数据库中的字段
    ip = forms.CharField(disabled=True, label="管理IP")

    class Meta:
        model = Device
        fields = ["ip", "dev_name", "vendor", "xinghao", "sn", "diqu", "weizhi", "jigui", "username", "password","enter", "snmp"]

        # 定义插件，针对password选项框加密
        widgets = {"password": forms.PasswordInput(render_value=True), "snmp": forms.PasswordInput(render_value=True)}

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            field.widget.attrs = {"class": "form-control"}


def dev_edit(request,nid):
    row_object=Device.objects.filter(id=nid).first()
    if request.method == "GET":
        form = DevEditModeForms(instance=row_object)
        return render(request,"dev_edit.html",{"form":form})

    form = DevEditModeForms(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/app02/devices/")
    return render(request,"dev_edit.html",{"form":form})




"""批量导入"""
def dev_all(request):

    if request.method == "POST":
        #1.获取用户上传的文件对象
        file_object = request.FILES.get("exc")

        #2.对象传递给openpyxl之家读取文件内容
        wb = load_workbook(file_object)
        sheet = wb.worksheets[0]

        #3.循环每一行数据;从第二行开始；一共13列
        for row in sheet.iter_rows(min_row=2,max_col=14):
            ip = row[0].value
            name = row[1].value
            dq = row[2].value
            wz = row[3].value
            jigui = row[4].value
            xinghao = row[5].value
            sn = row[6].value
            user = row[7].value
            pawd =row[8].value
            vendor = row[9].value
            snmp = row[10].value
            enter = row[11].value
            leixing = row[12].value
            port = row[13].value
            print(ip,name,dq,wz,jigui,xinghao,sn,user,pawd,vendor,snmp,enter,leixing,port)
            exists = Device.objects.filter(ip=ip).exists()
            if not exists:
                Device.objects.create(ip=ip,
                            dev_name=name,
                            diqu =dq,
                            weizhi =wz,
                            jigui=jigui,
                            xinghao=xinghao,
                            sn=sn,
                            username=user,
                            password = pawd,
                            vendor=vendor,
                            enter=enter,
                            snmp=snmp,
                            leixing=leixing,
                            ssh_port=port)
        return redirect('/app02/devices/')
    return  render(request,"piliangdaoru.html")




"""批量导出"""
def dev_export(request):
    if request.method == "GET":
        # 查询数据库所有数据
        data = Device.objects.all()
        # 定义下载格式
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment;filename=devices-list-%s.csv' % (datetime.now().strftime('%Y-%m-%d-%H-%M-%S'))

        #定义表并且写入到表格中
        header =  ["id","ip", "dev_name", "diqu", "weizhi","jigui" ,"xinghao","sn" ,"username", "password","vendor","snmp","enter","leixing","ssh_port"]
        writer = csv.writer(response)
        writer.writerow(header)

        # for 循环数据并将数据写入到表格中
        for i in data.values():
            obj_list = [(value) for key,value in i.items()]
            writer.writerow(obj_list)
        return response



"""模板下载"""
def dev_download(request):
    data = ["id","ip", "dev_name", "diqu", "weizhi","jigui" ,"xinghao","sn" ,"username", "password","vendor","snmp","enter","leixing","ssh_port" ]

    wb = openpyxl.Workbook()
    ws = wb.active

    ws.append(data)
    filename = 'muban.xlsx'
    wb.save(filename)

    # 打开Excel文件并读取其内容
    with open(filename, 'rb') as file:
        content = file.read()

    # 创建HttpResponse对象并返回
    response = HttpResponse(content, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = 'attachment; filename=' + filename
    return response





"""设备登陆"""
def dev_ssh(request,nid):
    row_object = Device.objects.filter(id=nid)
    for obj in row_object:
        ip = obj.ip
        user = obj.username
        pwd = obj.password
        base_pwd = str(base64.urlsafe_b64encode(pwd.encode("utf-8")),"utf-8")
        return redirect(f"http://127.0.0.1:8888/?hostname={ip}&username={user}&password={base_pwd}")















